package cn.fj.hrm.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

/**
 * 验证前端提交表单里面的两个密码要一致，难点就是要获取password字段和confirmPassword两个属性值
 * 自定义注解的验证规则实现类
 *  两个泛型：
 *      A：验证规则的自定义注解
 *      T：当前自定义注解使用到的字段类型
 *
 */
public class IdenticalPasswordValidator implements ConstraintValidator<IdenticalPassword, Object> {
    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        try {
            //1.获取字节码对象
            Class<?> aClass = object.getClass();

            //2.获取password和confirmPassword两个属性的值
            Field passwordField = aClass.getDeclaredField("password");
            Field confirmPasswordField = aClass.getDeclaredField("confirmPassword");
            passwordField.setAccessible(true);
            confirmPasswordField.setAccessible(true);
            String password = (String) passwordField.get(object);
            String confirmPassword = (String) confirmPasswordField.get(object);

            //3.比较
            return password.equals(confirmPassword);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
}
